/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bionic.ce.commands.systemacc;

import com.bionic.ce.beans.Bankacc;
import com.bionic.ce.beans.Systemacc;
import com.bionic.ce.businesslogic.BankAccService;
import com.bionic.ce.businesslogic.SystemAccService;
import com.bionic.ce.commands.ICommand;
import com.bionic.ce.manager.Config;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author MAXIM
 */
public class CommandWithdrawSelectedBankAccount implements ICommand {

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String page = null;
        try {
            Integer bankAccid = Integer.parseInt(request.getParameter("bankaccid"));
            Double withdrawSum = Double.parseDouble(request.getParameter("withdrawSum"));
            if (withdrawSum <= 0) {
                throw new NumberFormatException();
            }
            Bankacc bankAcc = BankAccService.returnCurrentBankAccInfo(bankAccid);
            //request.getSession().setAttribute("bankacc", bankAcc);
            Systemacc systemAcc = (Systemacc) request.getSession().getAttribute("systemacc");
            Double currentSystemAccSum = systemAcc.getAmount();
            if (withdrawSum <= currentSystemAccSum) {
                currentSystemAccSum -= withdrawSum;
                systemAcc.setAmount(currentSystemAccSum);
                SystemAccService.updateCurrentSystemacc(systemAcc);
                //request.setAttribute("depositmassage", "Your account was succesfully deposited");
                (new CommandGoToSystemAccountInfo()).execute(request, response);
                page = Config.getInstance().getProperty(Config.GOTOSYSTEMACCAOUNTSINFO);
            } else {
                request.setAttribute("withdrawerror", "You cant`t withdraw more than you have in your account");
                page = Config.getInstance().getProperty(Config.WITHDRAWGOTOBANKACCAOUNTSINFO);
            }
        }
        catch (IllegalArgumentException ex) {
            request.setAttribute("withdrawerror", "Please select bank account and enter correct withdraw amount");
            page = Config.getInstance().getProperty(Config.WITHDRAWGOTOBANKACCAOUNTSINFO);
        }

            return page;
        }
    
}